package org.csu.onlineedubackend.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.csu.onlineedubackend.dto.ChapterWithLessonsDTO;
import org.csu.onlineedubackend.entity.Chapter;
import org.csu.onlineedubackend.entity.Lesson;
import org.csu.onlineedubackend.mapper.ChapterMapper;
import org.csu.onlineedubackend.mapper.LessonMapper;
import org.csu.onlineedubackend.service.ChapterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
public class ChapterServiceImpl extends ServiceImpl<ChapterMapper, Chapter> implements ChapterService {
    
    @Autowired
    private ChapterMapper chapterMapper;
    
    @Autowired
    private LessonMapper lessonMapper;

    @Override
    public List<ChapterWithLessonsDTO> getChaptersWithLessons(Integer courseId) {
        List<Chapter> chapters = this.list(new QueryWrapper<Chapter>().eq("course_id", courseId).orderByAsc("sort_order"));
        List<ChapterWithLessonsDTO> result = new ArrayList<>();
        for (Chapter chapter : chapters) {
            List<Lesson> lessons = lessonMapper.selectList(
                    new QueryWrapper<Lesson>().eq("chapter_id", chapter.getId()).orderByAsc("sort_order")
            );
            ChapterWithLessonsDTO dto = new ChapterWithLessonsDTO();
            dto.setChapter(chapter);
            dto.setLessons(lessons);
            result.add(dto);
        }
        return result;
    }

    @Override
    public List<Chapter> getChaptersByCourseId(Integer courseId) {
        return chapterMapper.findByCourseId(courseId);
    }

    @Override
    public boolean createChapter(Chapter chapter) {
        // 如果没有设置排序，则设置为当前最大排序值+1
        if (chapter.getSortOrder() == null) {
            QueryWrapper<Chapter> wrapper = new QueryWrapper<>();
            wrapper.eq("course_id", chapter.getCourseId());
            wrapper.orderByDesc("sort_order");
            wrapper.last("LIMIT 1");
            Chapter lastChapter = this.getOne(wrapper);
            int nextSortOrder = (lastChapter != null && lastChapter.getSortOrder() != null) 
                ? lastChapter.getSortOrder() + 1 : 1;
            chapter.setSortOrder(nextSortOrder);
        }
        
        return this.save(chapter);
    }

    @Override
    public boolean updateChapterSort(Integer chapterId, Integer sortOrder) {
        Chapter chapter = this.getById(chapterId);
        if (chapter == null) {
            return false;
        }
        
        chapter.setSortOrder(sortOrder);
        return this.updateById(chapter);
    }

    @Override
    @Transactional
    public boolean deleteChapter(Integer chapterId) {
        // 先删除该章节下的所有课时
        QueryWrapper<Lesson> lessonWrapper = new QueryWrapper<>();
        lessonWrapper.eq("chapter_id", chapterId);
        lessonMapper.delete(lessonWrapper);
        
        // 再删除章节
        return this.removeById(chapterId);
    }
}
